package com.fckbug.action.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fckbug.Constants;
import com.fckbug.service.UserService;
import com.fckbug.util.JiaMi;
import com.fckbug.util.SpringContextHolder;
import com.fckbug.vos.Acc;
import com.mysql.jdbc.StringUtils;


/**
 * @struts.action path="/login"
 * @struts.action-forward name="result" path=""
 */
public class LoginAction extends Action{
	UserService userService = (UserService)SpringContextHolder.getBean("userService");
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	            HttpServletRequest request, HttpServletResponse response) throws Exception {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		if(StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)) {
			request.setAttribute("tip", "用户名和密码不能为空");
		} else {
			try{
				List data = userService.getUserByUsername(username);
				if(data.size() == 0) {
					request.setAttribute("tip", "没有该用户" + username);
				} else {
					Object[] objs = (Object[])data.get(0);
					String pwd = (String)objs[1];
					if(JiaMi.md5JiaMi(password).equals(pwd)) {
						request.getSession().setAttribute(Constants.SESSION_USER, new Acc((Integer)objs[0], username));
						String url = request.getParameter("url");
						if(!StringUtils.isNullOrEmpty(url)) {
							response.sendRedirect(url);
							return null;
							//return new RedirectingActionForward(rUrl);
						}
						return mapping.findForward("success");
					} else {
						request.setAttribute("tip", "密码或账号错误");
					}
				}
			} catch(Exception ex) {
				request.setAttribute("tip", "系统出错");
				ex.printStackTrace();
			}
		}
		return mapping.findForward("fail");
	}
}

